import { PageContainer } from "@ant-design/pro-components";
import {
  Button,
  Card,
  Select,
  Space,
  Descriptions,
  Empty,
  Flex,
  Image,
  message,
  Spin,
  DatePicker,
  InputNumber,
  Tag,
  Divider,
} from "antd";
import { connect, history } from "umi";
import { namespace } from "./configFile";
import { useState } from "react";
import { useParams } from "react-router-dom";
import SelectScheduleDialog from "./components/SelectScheduleDialog"; //选择课程弹窗
import SelectUserDialog from "./components/SelectUserDialog"; //选择会员信息弹窗
import dayjs from "dayjs";
import styles from "./styles.less";
import default_avater from "@/assets/imgs/default_avater.png";
import Https from "@/utils/Https";
import { disabledDate, effectiveTypeList, VipCategoryEnum, vipTypeList } from "@/utils/common";
import moment from "moment";
import { RedoOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import { calculate } from "./interface";
const Page = (props) => {
  const [scheduleOpen, setScheduleOpen] = useState(false); //选择课程弹窗
  const [userOpen, setUserOpen] = useState(false); //选择学员弹窗
  const [scheduleInfo, setScheduleInfo] = useState<any>(); //课程信息
  const [studentInfo, setStudentInfo] = useState<any>(); //学员信息
  const [cardInfo, setCardInfo] = useState<any>(); //会员卡信息
  const [cardList, setCardList] = useState([]); //会员卡列表
  const [deductObj, setdeductObj] = useState<any>(); //扣除数信息
  const [cardId, setCardId] = useState<any>();
  const [tradeHours, setTradeHours] = useState([]);
  const [selectTime, setSelectTime] = useState<any>();
  const [remark, setRemark] = useState("");
  const params = useParams();
  const [loading, setLoading] = useState(false);
  const [activeIndex, setActiveIndex] = useState(-1);
  const [defaultTime, setDefaultTime] = useState();
  const [appointPeopleNum, setAppointPeopleNum] = useState(1);
  let current = moment().format("YYYY-MM-DD");
  //选定了学员
  const selectedUser = (data) => {
    setStudentInfo(data);
    setRemark("");
    closeDialog();
    setAppointPeopleNum(1);
  };
  //选定了课程
  const selectedSchedule = (data) => {
    setScheduleInfo(data);
    getCardListByUserId(data.id);
    setRemark("");
    setCardId(null);
    setCardInfo(null);
    setStudentInfo(null);
    setdeductObj(null);
    setSelectTime(null);
    setTradeHours([]);
    setScheduleOpen(false);
  };

  //营业时间
  const getTradeHours = async (venueId, id, vipCardId, dateString?) => {
    let obj = {
      venueId,
      currentDate: dateString,
      //非私教课
      courseScheduleId: id,
      //私教课
      courseId: id,
      courseType: params.id,
      vipCardId,
    };
    setLoading(true);
    setActiveIndex(-1);
    setSelectTime(null);
    let res = await Https.get("/proxy/appoint/getTradeHours", obj, true);
    if (res.code == 200 && res.data) {
      let list = calculate(res.data, dateString);
      setTradeHours(list);
    } else {
      message.error(res.msg);
      setTradeHours([]);
    }
    setLoading(false);
  };

  //查询课程下的会员卡
  const getCardListByUserId = async (id) => {
    let res: any = await Https.get(
      "/proxy/appoint/getUsableCardList",
      {
        courseId: id,
      },
      true
    );
    if (res && res.code == 200) {
      setCardList(res.data.records || []);
    } else {
      setCardList([]);
    }
  };

  const getTipsText = (status: any) => {
    // 0过期 1可用 2被约 3休息 4限定
    switch (status) {
      case 0:
        return { text: "过期", color: "#B9B9B9", background: "#f5f5f5" };
      case 1:
        return { text: "可用" };
      case 2:
        return { text: "被约", color: "#FF0000" };
      case 3:
        return { text: "休息", color: "#B9B9B9", background: "#f5f5f5" };
      case 4:
        return { text: "限定", color: "#B9B9B9", background: "#f5f5f5" };
    }
  };

  const saveOrder = async () => {
    let data = {
      wechatUserId: studentInfo.wechatUserId,
      userCardId: studentInfo.id,
      courseId: scheduleInfo.id,
      currentDate: dayjs(defaultTime).format("YYYY-MM-DD"),
      bookStartTime: moment(selectTime.startTime).format("YYYY-MM-DD HH:mm"),
      bookEndTime: moment(selectTime.endTime).format("YYYY-MM-DD HH:mm"),
      remark,
      appointPeopleNum,
    };
    setLoading(true);
    let res = await Https.post(
      "/proxy/appoint/proxyAppointSavePrivate",
      data,
      true
    );
    setLoading(false);
    if (res.code === 200) {
      message.success("操作成功");
      history.go(-1);
    } else {
      message.error(res.msg);
    }
  };

  //关闭弹窗
  const closeDialog = () => {
    setScheduleOpen(false);
    setUserOpen(false);
  };
  //获取会员卡扣除数
  const getCardAndCourseId = async (id) => {
    let res = await Https.get(
      "/proxy/appoint/getUsableCourseByCardAndCourseId",
      { courseId: scheduleInfo.id, vipcardId: id },
      true
    );
    if (res && res.code == 200) {
      let obj = {
        deductNum: res.data.deductNum,
      };
      setdeductObj(obj);
    } else {
      message.error(res.msg);
    }
  };
  //计算预约结束时间是否在可用时间范围内
  const calcDuration = (item, index) => {
    let objList: any = [...tradeHours];
    let endTime = moment(item.time)
      .add(scheduleInfo.courseDuration, "minute")
      .format("YYYY-MM-DD HH:mm:ss");
    let startIndex = index;
    let endIndex = objList.findIndex((item) => {
      return item.time == endTime;
    });
    if (endIndex > -1) {
      let timeList = tradeHours.slice(startIndex, endIndex);
      let hasAppointment = timeList.every(function (o) {
        return o.status == 1;
      });
      if (hasAppointment) {
        setSelectTime({
          startTime: item.time,
          endTime,
        });
      } else {
        message.error(
          `${moment(item.time).format("HH:mm")}~${moment(endTime).format(
            "HH:mm"
          )}不可预约`
        );
      }
    } else {
      message.error(
        `${moment(item.time).format("HH:mm")}~${moment(endTime).format(
          "HH:mm"
        )}超出运营时间`
      );
    }
  };

  //过滤会员卡
  const filterOption = (
    input: string,
    option?: { children: string; value: string }
  ) => {
    return option.children.toLowerCase().includes(input.toLowerCase());
  };
  return (
    <Spin spinning={loading}>
      <PageContainer
        key="PersonalOrder"
        className={styles.orderCourse}
        title={`${
          params.id == "1" ? "私教课" : params.id == "2" ? "团课" : "训练营"
        }代客预约`}
        onBack={() => {
          history.go(-1);
        }}
        footer={[
          <>
            <div className={styles.footer_box}>
              {selectTime && (
                <span>
                  预约时间:
                  {moment(selectTime.startTime).format("YYYY-MM-DD HH:mm")}-
                  {moment(selectTime.endTime).format("HH:mm")}
                </span>
              )}
              {cardInfo && deductObj && (
                <span style={{ marginLeft: "10px" }}>
                  扣除: {cardInfo.vipcardName},
                  {cardInfo.vipType == 1
                    ? (Number(deductObj.deductNum) / 100).toFixed(2)
                    : Number(deductObj.deductNum)}
                  {vipTypeList[cardInfo.vipType].status}
                </span>
              )}
            </div>
            <Space key="Space">
              <Button
                key="cancel"
                onClick={() => {
                  history.push("/course/personal");
                }}
                size="large"
              >
                取消
              </Button>
              <Button
                type="primary"
                size="large"
                key="save"
                style={{ marginLeft: "20px" }}
                disabled={
                  !scheduleInfo || !cardInfo || !studentInfo || !selectTime
                }
                loading={loading}
                onClick={() => {
                  saveOrder();
                }}
              >
                预约
              </Button>
            </Space>
          </>,
        ]}
      >
        <Card
          title="课程信息"
          extra={
            <Button type="primary" onClick={() => setScheduleOpen(true)}>
              选择课程
            </Button>
          }
        >
          {!scheduleInfo ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <div>
                  暂无数据 <br /> 请先选择课程
                </div>
              }
            />
          ) : (
            <Descriptions title="">
              <Descriptions.Item label="课程名称">
                {scheduleInfo.courseName || "-"}
              </Descriptions.Item>
              <Descriptions.Item label="课程分类">
                {scheduleInfo.courseCategoryName || "-"}
              </Descriptions.Item>
              <Descriptions.Item label="所属场馆">
                {scheduleInfo.venueName || "-"}
              </Descriptions.Item>
              <Descriptions.Item label="课程教练">
                {scheduleInfo.courseCoachName || "-"}
              </Descriptions.Item>
              <Descriptions.Item label="课程时长">
                {scheduleInfo.courseDuration
                  ? scheduleInfo.courseDuration + "分钟"
                  : "-"}
              </Descriptions.Item>
              <Descriptions.Item label="授课模式">
                {scheduleInfo.id ? "一对一" : "-"}
              </Descriptions.Item>
            </Descriptions>
          )}
        </Card>
        <Card
          title="预约信息"
          style={{ marginTop: "20px" }}
          extra={
            <Select
              placeholder="请选择会员卡"
              showSearch
              value={cardId}
              filterOption={filterOption}
              onChange={(val) => {
                let cardObj = cardList.filter(function (o) {
                  return o.id == val;
                })[0];
                setRemark("");
                setStudentInfo(null);
                setdeductObj(null);
                setSelectTime(null);
                setTradeHours([]);
                getCardAndCourseId(val);
                getTradeHours(
                  scheduleInfo.venueId,
                  scheduleInfo.id,
                  val,
                  dayjs().format("YYYY-MM-DD")
                );
                setCardInfo(cardObj);
                setCardId(val);
                setDefaultTime(dayjs(current, "YYYY-MM-DD"));
              }}
              getPopupContainer={(triggerNode) => triggerNode.parentElement}
              style={{ width: "500px" }}
              options={cardList}
              fieldNames={{
                label: "vipcardName",
                value: "id",
              }}
              optionRender={(option: any) => {
                const e = option.data;
                return e ? (
                  <>
                    {e.isUniversal == "1" && (
                      <Tag style={{ marginRight: "8px" }} color="processing">
                        通
                      </Tag>
                    )}
                    {
                      <Tag style={{ marginRight: "10px" }} color="purple">
                        {VipCategoryEnum[e.vipCategory].shortName}
                        <Divider type="vertical"></Divider>
                        {vipTypeList[e.vipType].shortName}
                      </Tag>
                    }
                    {e.vipcardName}
                    {
                      <Tag style={{ marginLeft: "10px" }}>
                        {e.effectiveValue +
                          "" +
                          effectiveTypeList[e.effectiveType].text}
                        {e.vipType != 2 && (
                          <>
                            <Divider type="vertical"></Divider>
                            {e.vipType == 1
                              ? (Number(e.cardLimit) / 100).toFixed(2) +
                                vipTypeList[e.vipType].status
                              : e.vipType == 3
                                ? Number(e.cardLimit) +
                                  vipTypeList[e.vipType].status
                                : ""}
                          </>
                        )}
                      </Tag>
                    }
                  </>
                ) : (
                  "-"
                );
              }}
            />
          }
        >
          {!cardInfo ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <div>
                  暂无数据 <br /> 请先选择会员卡
                </div>
              }
            />
          ) : (
            <>
              <Descriptions
                title={
                  <div>
                    会员卡信息
                    <DatePicker
                      value={defaultTime}
                      onChange={(date, dateString) => {
                        setDefaultTime(dayjs(dateString, "YYYY-MM-DD"));
                        setStudentInfo(null);
                        setRemark("");
                        setAppointPeopleNum(1);
                        getTradeHours(
                          scheduleInfo.venueId,
                          scheduleInfo.id,
                          cardId,
                          dateString
                        );
                      }}
                      disabledDate={disabledDate}
                      allowClear={false}
                      style={{ marginLeft: "15px" }}
                    />
                    <Button
                      type="primary"
                      style={{ marginLeft: "15px" }}
                      size="small"
                      icon={<RedoOutlined />}
                      onClick={() => {
                        getTradeHours(
                          scheduleInfo.venueId,
                          scheduleInfo.id,
                          cardId,
                          dayjs(defaultTime).format("YYYY-MM-DD")
                        );
                      }}
                    >
                      刷新时间
                    </Button>
                  </div>
                }
              >
                <Descriptions.Item label="卡名称">
                  {cardInfo.vipcardName || "-"}
                </Descriptions.Item>
                <Descriptions.Item label="卡种类">
                  {cardInfo.vipCategory == 1 ? "正式卡" : "体验卡"}
                </Descriptions.Item>
                <Descriptions.Item label="卡类型">
                  {cardInfo.vipType && vipTypeList[cardInfo.vipType].text}
                </Descriptions.Item>
              </Descriptions>
              <div className={styles.tradeHours_box}>
                {tradeHours &&
                  tradeHours.length > 0 &&
                  tradeHours.map((item: any, index) => (
                    <div
                      className={`${styles.tradHourse_item} ${
                        item.status == 1 ? styles.tradHourse_hover : ""
                      } ${index == activeIndex ? styles.tradHourseActive : ""}`}
                      key={index}
                      onClick={() => {
                        calcDuration(item, index);
                        setActiveIndex(index);
                      }}
                      style={{
                        color: getTipsText(item.status).color
                          ? getTipsText(item.status).color
                          : "",
                        background: getTipsText(item.status).background
                          ? getTipsText(item.status).background
                          : "",
                        cursor: item.status != "1" ? "default" : "pointer",
                        pointerEvents: item.status != 1 ? "none" : "",
                      }}
                    >
                      {item.time && moment(item.time).format("HH:mm")}
                      {item.status != 1 && (
                        <div
                          className={styles.tradHourse_tips}
                          style={{
                            color: getTipsText(item.status).color
                              ? getTipsText(item.status).color
                              : "",
                          }}
                        >
                          {getTipsText(item.status).text}
                        </div>
                      )}
                    </div>
                  ))}
              </div>
              <Card
                title="会员信息"
                style={{ marginTop: "20px" }}
                extra={
                  <Button type="primary" onClick={() => setUserOpen(true)}>
                    选择学员
                  </Button>
                }
              >
                {!studentInfo ? (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={
                      <div>
                        暂无数据 <br /> 请先选择会员
                      </div>
                    }
                  />
                ) : (
                  <Flex justify="flex-start">
                    <Flex style={{ flex: 1 }}>
                      <Image
                        src={studentInfo.avatar || default_avater}
                        width={100}
                        height={100}
                      />
                    </Flex>
                    <Flex
                      justify="flex-start"
                      wrap="wrap"
                      style={{ width: "80%" }}
                      className={styles.flex_info}
                    >
                      <div>手机号码： {studentInfo.tel || "-"}</div>
                      <div>
                        性别：
                        {studentInfo.sex == 0
                          ? "男"
                          : studentInfo.sex == 1
                          ? "女"
                          : "保密"}
                      </div>
                      <div>会员名称： {studentInfo.nickName || "-"}</div>
                      <div>
                        有效期：
                        {studentInfo.effectiveTime
                          ? moment(studentInfo.effectiveTime).format(
                              "YYYY-MM-DD"
                            )
                          : "-"}
                      </div>
                      <div>
                        卡余额：
                        {studentInfo.vipType != 2
                          ? studentInfo.vipType == 1
                            ? Number(studentInfo.currentCardLimit) / 100 +
                              vipTypeList[studentInfo.vipType].status
                            : studentInfo.currentCardLimit +
                              vipTypeList[studentInfo.vipType].status
                          : "-"}
                      </div>
                      <div>
                        <span style={{ color: "red" }}>*</span> 预约人数：
                        <InputNumber
                          min={1}
                          precision={0}
                          placeholder="请输入预约人数"
                          controls={false}
                          value={appointPeopleNum}
                          onChange={(e) => {
                            e = Number(e);
                            if (e < 1) {
                              message.error("预约人数不能小于1");
                              setAppointPeopleNum(1);
                            } else {
                              setAppointPeopleNum(e);
                            }
                          }}
                        />
                      </div>
                      <div style={{ width: "100%", display: "flex" }}>
                        <span style={{ width: "50px" }}>备注：</span>
                        <TextArea
                          showCount
                          maxLength={100}
                          placeholder="请输入备注"
                          value={remark}
                          onChange={(e) => {
                            let { value } = e.target;
                            setRemark(value);
                          }}
                          style={{
                            height: 120,
                            resize: "none",
                          }}
                        />
                      </div>
                    </Flex>
                  </Flex>
                )}
              </Card>
            </>
          )}
        </Card>
        <SelectScheduleDialog
          {...props}
          type={params.id}
          show={scheduleOpen}
          close={() => closeDialog()}
          submit={(data) => selectedSchedule(data)}
        />
        <SelectUserDialog
          {...props}
          classInfo={cardInfo}
          defaultTime={defaultTime}
          show={userOpen}
          close={() => closeDialog()}
          submit={(data) => selectedUser(data)}
        />
      </PageContainer>
    </Spin>
  );
};

export default connect((state) => {
  return {
    ...state[namespace],
    submitLoading: state.loading.effects[`${namespace}/submitItem`],
  };
})(Page);
